<template>
  <div>
    <div class="node" v-has="{action: 'sys:config:list', effect: 'move'}">
      <div :class="[$style.search_box, $style.topSelect]">
        <SearchInput
          placeholder="参数名称"
          label="参数名称"
          style="margin-right:20px"
          :value="names"
          :onChange="(val) => changeSearch('names',val)"
          :onBlur="getQueryData"
        />
        <div :class="$style.searchBox1" style="margin-left: 20px">
        <el-button  size="small" plain icon="el-icon-search" @click="getQueryData">查询</el-button>        
      </div>
      </div>
      <Panel title="参数配置" :intro="intro">
        <!-- <div slot='ext' :class="$style.examine">
          <div class="adopt" @click="()=>editStoreAdd()">新增</div>
      </div> -->
      <TableEncapsulation
        slot="body"
        :tableConfig="tableConfig"
        :tableData="tableData"
      >
      <template slot="operation" slot-scope="operation">
            <el-button size="mini" icon="el-icon-edit"
              v-has="{action: 'sys:config:update', effect: 'move'}"
              @click="()=>editStore(operation.row)"
            >编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete"
              v-has="{action: 'sys:config:delete', effect: 'move'}"
              @click="()=>remove(operation.row.id)"
            >删除</el-button>
          </template>
          <TablePager
            slot="pager"
            v-if="pager.use"
            :size="pager.size"
            :pageChange="pageChange"
            :show-total="pager.showTotal"
            :total="pager.total"
            :current="pager.current"
          >
            <span class="demonstration">GO></span>
          </TablePager>
      </TableEncapsulation>
      </Panel>

      <ModalPanel 
        :visible='visible'
        title="编辑"
        :onCancel="onCancel"
        :class="$style.bannerDialog"
        :onOk="onSubmit">
        <div>
          <ModifyForm
            :hiddenBtn='true'
            :editColumn='editColumn'
            :updateData="updateData"
            labelWidth='100px'
            ref="configModal"
            :class="$style.ModifyForm"
            :temporaryData='modalData'>
            <div slot="key">
              <el-form-item  label="名称" >
                  <el-input 
                  :placeholder="'请输入名称'" 
                  v-model="key">
                  <!-- <template v-if="item.append" slot="append">{{item}}</template> -->
                </el-input>
                </el-form-item>
            </div>
            <div slot="remark">
              <div class="own">
                <el-form-item  label="备注" >
                  <el-input 
                  :placeholder="'请输入备注'" 
                  v-model="mark">
                  <!-- <template v-if="item.append" slot="append">{{mark}}</template> -->
                </el-input>
                </el-form-item>
              </div>
            </div>
            <div slot="setParam">
              <template v-if="valtype == 1">
                <div v-for="(item, key) in temporaryData"  class="own" :key="key" style="margin-bottom:10px">
                <el-form-item  :label="item.desc" >
                  <el-input 
                  :key="key"
                  :placeholder="'请输入'+item.desc" 
                  v-model="valueData[item.key]">
                  <template v-if="item.append" slot="append">{{valueData[item.key]}}</template>
                </el-input>
                </el-form-item>
              </div>
              </template>
              <div v-else-if="valtype == 3">
                
                <el-form-item  label="配置值" >
                <el-input 
                  type="number"
                  placeholder="请输入值" 
                  v-model="configData">
                {{item}}
                </el-input>
                </el-form-item>
              </div>
              <div v-else>
                
                <el-form-item  label="配置值" >
                <el-input 
                
                  placeholder="请输入值" 
                  v-model="configData">
                {{item}}
                </el-input>
                </el-form-item>
              </div>
              
          </div>
          </ModifyForm>
        </div>
      </ModalPanel>
      <ModalPanel 
        :visible='visibleAdd'
        title="添加"
        :onCancel="onCancelAdd"
        :class="$style.bannerDialog"
        :onOk="onSubmit"
        :showFooter="false"
        >
        <div>
          <Panel title="添加参数" >
            <div slot="body" class="time-input">
              
                <div class="" style="margin: 20px 0;display: flex;align-items: flex-end;background: #f1f4f7;justify-content: space-around;padding: 10px;color: #000">
                    <div class="input-box">
                         <span class="input-title">名称(key)：<span :class="$style.red">*</span></span>
                         <el-input v-model="key" placeholder="请使用英文"></el-input>
                    </div>
                    <div class="input-box">
                         <span class="input-title">参数备注(mark):<span :class="$style.red">*</span></span>
                         <el-input v-model="mark" placeholder="备注"></el-input>
                    </div>
                    <div class="input-box">
                      <span class="input-title">是否可删除:</span>
                      <el-select v-model="canDel" placeholder="是否可删除">
                        <el-option
                         v-for="item in isDel"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
                       </el-option>
                     </el-select>
                 </div>
                </div>
                <el-button  type="danger" @click="addIds()" style="margin-left:10px;margin-bottom:20px" title="在下面加一行费率组分段">添加配置项</el-button>
              <el-form :inline="true" class="demo-form-inline" id="formData">
                <div>
                  <el-table
                    :data="formSku.foodSkuSpeciftcations"
                    style="width: 100%">
                    <el-table-column
                      label="配置项关键字(key)"
                      >
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.key" placeholder="请使用英文"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="配置项值"
                      >
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.default" placeholder="参数值"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="配置项描述"
                     >
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.desc" placeholder="配置项描述"></el-input>
                      </template>
                    </el-table-column>
                   
                    <el-table-column
                      label="操作"
                      >
                      <template slot-scope="scope">
                        <el-button  type="primary"  @click="deleteIds(scope.$index)" style="margin-left:10px">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-form>
              <div :class="$style.btns">
                <el-button type="primary" @click="addConfig">提交</el-button>
              </div>
            </div>
           
            </Panel>
        </div>
      </ModalPanel>
    </div>
    <div style="display: none;width:100%;height:100%;margin: auto;" v-has="{action: 'sys:config:list', effect: 'noPremiss'}">
      <NoPremission></NoPremission>
    </div>
  </div>
</template>
<script>
import request from "@/tools/request";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import SearchInput from "@/components/SearchInput";
import ModifyForm from "@/components/ModifyForm";
import ModalPanel from "@/components/ModalPanel";
import { objectFilter } from "@/tools/array";
export default {
  name: "sysConfig",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    SearchInput,
    ModifyForm,
    ModalPanel
  },
  data() {
    return {
      intro:{
        title: '',
        content: `功能说明：系统参数配置，请勿随意修改`
      },
      visible:false,
      modalData:{},
      tableData: [],
      valueData:{},
      temporaryData: {},
      configData:'',
      valtype:'json',//1json 2数字 3字符串
      query: {
        page: 1,
        type: 2
      },
      val:{},
       pager: {
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      names: '',
      operation: true,
      name: '',
      key:'',
      mark:'',
      //添加
      key:'', 
      mark: '',
      canDel: false,
      isDel: [
        {value: false,label: '否'},
        {value: true,label: '是'},
      ],
      visibleAdd:false,
      modalDataAdd: {},
      formSku: {
        foodSkuSpeciftcations: [{"key": '','desc': '','default': ''}],
      },
      editColumn: [
        {
          name: "",
          prop: "key",
          type: "other",
          required: false,
          width: 20,
          slotName: "key",
        },
        {
            name: "",
            type: "other",
            slotName: "remark",
            prop: "mark",
            width: 20,
            required: false,
          },
        {
          name: "",
          prop: "val",
          type: "other",
          slotName: "setParam",
          required: false,
          width:20
        },
      ],
    };
  },
  created() {
    this.getQueryData();
  },
  computed: {
    tableConfig () {
      return {
        selection: true,
        columnConfig: [
          {
            label: "编号",
            type: "text",
            prop: "id",
            align: "center"
          },
          {
            label: "名称",
            type: "text",
            prop: "key",
            align: "center"
          },
          {
            label: "备注",
            type: "text",
            prop: "mark",
            align: "center"
          },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:180
          }
        ].filter(Boolean)
        }
    }
  },
  methods: {
    async getQueryData() {
      let key = this.names
      let page = this.pager.current
      let search = objectFilter({key, page})
      const res = await request({
        url: "/sys/config/list",
        method: "POST",
        data: search
      });
      this.tableData = res.page.list
      this.pager.total = res.page.totalCount
      this.pager.current = res.page.currPage
    },
    pageChange(val) {
      this.pager.current = val;
      this.getQueryData();
    },
    changeSearch(key, val) {
      this[key] = val;
      this.pager.current = 1;
    },
    editStore(rowData){
      let jsonDta = JSON.parse(rowData.val)
      let arr = rowData.valParam
      this.valueData = jsonDta
      this.temporaryData = arr
      this.valtype = rowData.valType
      this.configData = rowData.val
      this.mark   = rowData.mark
      this.key   = rowData.key
       this.modalData ={ ...rowData }
      this.visible = true
      // this.$router.push({ path: "/editStore",query:{id:id} })
    },
    editStoreAdd(){
      this.mark = ''
      this.key = ''
      this.visibleAdd = true
      this.modalDataAdd ={ }
    },
    onCancel(){
      this.visible = false
    },
    async onSubmit(){
      this.$refs['configModal'].onSubmit()
    },
    async updateData(values){
      let val
      if(this.valtype == 1){
         val = JSON.stringify(this.valueData)
      }else{
        val = this.configData
      }
      // return
      let key = this.key
      let mark = this.mark
      const { id } = values
      let url = values.id ? "/sys/config/update" : "/sys/config/add"
      let msg = values.id ? "编辑成功" : "添加成功"
      let res = await request({
        url: url,
        method: "POST",
        data: { id, key, mark, val, view:1 }
      })
      if( res.code !== 0) return
      this.$message.success(msg)
      this.visible = false
      this.getQueryData()
    },
    commentDetail(id){
      this.$router.push({ path: "/storeDetail",query:{id:id,type: "toview"} })
    },

    // 添加
    onCancelAdd(){
      
      this.visibleAdd = false
    },
    addIds(){
      this.formSku.foodSkuSpeciftcations.push({})
    },
    deleteIds(index) {
      this.formSku.foodSkuSpeciftcations.splice(index, 1)
    },
    async addConfig(){
      console.log('this.formSku.foodSkuSpeciftcations',this.formSku.foodSkuSpeciftcations)
      // return
      let data = this.formSku.foodSkuSpeciftcations
      if(data.length<1){
        this.$message.error('至少包含一条配置信息')
        return
      }
      var val ={}
      var flag = 1

      data.map(item => {
        if(!item.key){
          flag = 0
        }else{
          var keys = item.key
          val[keys] = item.default
        }
        
      })
      if(!flag){
        this.$message.error('请完成配置项填写')
        return
      }
      val = JSON.stringify(val)
      console.log('val', val)
      // return
      let key = this.key
      if(!key){
        this.$message.error('请输入参数名')
        return
      }
      let mark = this.mark
      if(!mark){
        this.$message.error('请输入参数备注')
        return
      }
      let canDel = this.canDel
      let url = '/sys/config/add'
      let msg =  "添加成功"
      let res = await request({
        url: url,
        method: "POST",
        data: { key, mark, val, canDel, valParam:  data, valType :1}
      })
      if( res.code !== 0) return
      this.$message.success(msg)
      this.visibleAdd = false
      this.getQueryData()
    },

    //添加 ///end
    remove(id){
       this.$confirm('确认删除吗', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        let res = await request({
          url: '/sys/config/delete',
          method: 'POST',
          dataType: 'json',
          data:[id]
        })
        if(res.code !==0) return
        this.$message.success('删除成功')
        if(this.tableData.length===1 && this.pager.current>1)
          this.$set(this.pager,'current', this.pager.current-1)
        this.getQueryData()
      })
    },
  }
}
</script>
<style lang='scss' module>
.examine{
    display: flex;
    align-items: center;
    :global{
        div{
            color: #fff;
            padding: 10px;
            margin: 0 10px;
            border-radius: 2px;
            font-size: 14px;
            cursor: pointer;
            min-width: 60px;
            text-align: center;
        }
        .adopt{
                background: #409EFF;
        }
    }
}
.search_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  :global {
    .el-input {
      width: 150px;
    }
    .el-select {
      .el-input {
        width: 90px;
      }
    }
    .el-input__icon {
      line-height: 27px;
    }
    .el-range-separator{
      line-height: 26px;
    }
  }
}
.input-arr{
  margin-left: 0;
}

.topSelect {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}
.el-form-item__content{
  margin-left: 0;
}
.btns{
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
.red {
  color: red;
}
</style>